package ThreadPoolDemo.bilibiliThread;

import java.util.Random;

public class ThreadLocalTest {

	private static ThreadLocal<Integer> xLocal = new ThreadLocal<Integer>();
	private static ThreadLocal<MyThreadScopeDate> myThreadLocal = new ThreadLocal<MyThreadScopeDate>();

	public static void main(String[] args) {
		for (int i = 0; i < 2; i++) {

			new Thread(new Runnable() {

				@Override
				public void run() {
					int data = new Random().nextInt();
					System.out.println(Thread.currentThread().getName()
							+ "has put data:" + data);
					xLocal.set(data);
					/*
					 * MyThreadScopeDate dataDate = MyThreadScopeDate.
					 * dataDate.setAgeString("123" + data);
					 * dataDate.setNameString("321" + data);
					 * myThreadLocal.set(dataDate);
					 */
					MyThreadScopeDate.getThreadInstance().setAgeString(
							"age" + data);
					MyThreadScopeDate.getThreadInstance().setNameString(
							"name" + data);
					new A().get();
					new B().get();

				}
			}).start();
		}
	}

	static class A {

		public void get() {
			int data = xLocal.get();
			MyThreadScopeDate myDate = MyThreadScopeDate.getThreadInstance();
			System.out.println(myDate.toString());
			System.out.println("A from " + Thread.currentThread().getName()
					+ "has put data:" + data);
		}
	}

	static class B {
		public void get() {
			int data = xLocal.get();
			MyThreadScopeDate myDate = MyThreadScopeDate.getThreadInstance();
			System.out.println(myDate.toString());
			System.out.println("B from " + Thread.currentThread().getName()
					+ "has put data:" + data);
		}
	}
}

class MyThreadScopeDate {

	private MyThreadScopeDate() {
	};

	public static MyThreadScopeDate getThreadInstance() {
		MyThreadScopeDate instanceDate = map.get();
		if (instanceDate == null) {
			instanceDate = new MyThreadScopeDate();
			map.set(instanceDate);
		}
		return instanceDate;
	}

	private static ThreadLocal<MyThreadScopeDate> map = new ThreadLocal<MyThreadScopeDate>();
	private String nameString;
	private String ageString;

	public String getNameString() {
		return nameString;
	}

	public void setNameString(String nameString) {
		this.nameString = nameString;
	}

	public String getAgeString() {
		return ageString;
	}

	public void setAgeString(String ageString) {
		this.ageString = ageString;
	}

	@Override
	public String toString() {
		return "MyThreadScopeDate [nameString=" + nameString + ", ageString="
				+ ageString + "]";
	}

}
